'''
Created on Jun 29, 2012

@author: xding
'''

from sqllib import graph_table_list, gtfs_table_list, global_table_list, table_sql
from shortcuts import execute_sql, execute_insert, execute_select, log_info


def init_dataset_schema():
    log_info("Init datasets")
    for table in global_table_list:
        sql = table_sql[table] % "MyISAM"
        execute_sql(sql, print_sql=False)
    create_tables("gtfs", "MERGE");


def drop_tables(dataset_name):
    log_info("Drop dataset " + dataset_name)
    for table in gtfs_table_list | graph_table_list:
        table_full_name = dataset_name + "_" + table
        execute_sql("DROP TABLE IF EXISTS " + table_full_name, print_sql=False)
    execute_sql("DELETE FROM gtfs_dataset WHERE dataset_name = '%s'" % dataset_name, print_sql=False)


def create_tables(dataset_name, engine):
    log_info("Create dataset " + dataset_name)
    dataset_id = execute_insert("gtfs_dataset", [("dataset_name", dataset_name)], print_sql=False)
    for table in gtfs_table_list | graph_table_list:
        sql = table_sql[table] % (dataset_name, dataset_id, engine)
        execute_sql(sql, print_sql=False)
    return dataset_id


def union(dataset_list):
    if dataset_list is None:
        datasets = execute_select("SELECT dataset_name FROM gtfs_dataset WHERE dataset_name <> 'gtfs'")
        dataset_list = [item[0] for item in datasets]
    log_info("Union gtfs tables " + ",".join(dataset_list))
    for table in gtfs_table_list | graph_table_list:
        unions = ",".join([dataset_name + "_" + table for dataset_name in dataset_list])
        sql = "ALTER TABLE gtfs_%s UNION=(%s)" % (table, unions)
        execute_sql(sql, print_sql=True)

